--[[ Utility Functions ]]

function warnParticle( unit ,ability )
	local partID = ParticleManager:CreateParticle("particles/darkmoon_creep_warning.vpcf",PATTACH_ABSORIGIN,unit)
	ParticleManager:SetParticleControlEnt( partID, 0, unit, PATTACH_ABSORIGIN_FOLLOW, nil, unit:GetOrigin(), true )
	local radius = 300
	if ability then
		radius = radius or ability:GetSpecialValueFor("radius")
	end
	ParticleManager:SetParticleControl( partID, 1, Vector( radius, radius, radius ) ) --半径
	ParticleManager:SetParticleControl( partID, 15, Vector( 255, 0, 0 ) )  --颜色
	unit.warn_particle = partID
end

---------------------------------------------------------------------------
-- Broadcast messages to screen
---------------------------------------------------------------------------
function BroadcastMessage( sMessage, fDuration,iPlayer )
	local centerMessage = {
		message = sMessage,
		duration = fDuration
	}
	if iPlayer then
		centerMessage["player_id"] = iPlayer
	end
	FireGameEvent( "show_center_message", centerMessage )
end

function dropAllItems(unit)
	local uindex = unit:entindex()
	local pos = unit:GetAbsOrigin()
	for i=0,14 do
		local item = unit:GetItemInSlot(i)
		if item then

			local orderDrop = {
				UnitIndex = uindex,
				OrderType = DOTA_UNIT_ORDER_DROP_ITEM,
				AbilityIndex = item:entindex(),
				Position = pos
			}
			ExecuteOrderFromTable(orderDrop)
			
		end
	end
end

function updateRank(damage,killer,killed)
	--伤害统计
	local team1 = killer:GetTeamNumber()
	local team2 = killed:GetTeamNumber()
	if team1 == team2 then
		return 
	end
	local owner = killer
	if killer._owner then
		owner = EntIndexToHScript(killer._owner)
	end
	local playerID = owner:GetPlayerOwnerID()
	if playerID < 0 then
		return
	end
	GameRules.damage[playerID+1] = GameRules.damage[playerID+1] + damage
	local teamNum = team1
	GameRules.damage_team[teamNum] = GameRules.damage_team[teamNum] + damage 
	CustomNetTables:SetTableValue( "primInfo", string.format( "%d", playerID ), {damage = GameRules.damage[playerID+1]} )
	CustomNetTables:SetTableValue( "teamInfo", string.format( "%d", teamNum ), {damage = GameRules.damage_team[teamNum]} )
end

function showWarn(message,player_id)
	local hPlayer
	local _t = type(player_id)
	if _t == 'number' then
		hPlayer = PlayerResource:GetPlayer(player_id)
	else
		hPlayer = player_id:GetPlayerOwner()
	end
	
	CustomGameEventManager:Send_ServerToPlayer(hPlayer,"S2C_ERROR_MSG",{text = message})
end
--判断是否物品栏满了
function isFullInvent(hero)
	for i=0,5 do
		local item = hero:GetItemInSlot(i)
		if not item then
			return false
		end
	end
	return true
end

function addItemToBackPack(hero,itemIndex)
	local playerId = hero:GetPlayerOwnerID()
	return roleData.addItemToBackPack(playerId,itemIndex)
end

function addItemToPlayer(hero,itemIndex)
	for i=0,5 do
		local item = hero:GetItemInSlot(i)
		if not item then
			CreateNewItem()
			return true
		end
	end
	--物品栏已满 放入背包
	return addItemToBackPack(hero,itemIndex)
end
--由前端判断是否与背包有关
function moveItem(hero,itemIndex,itemIndex2)

end

local function dump_value_(v)
    if type(v) == "string" then
        v = "\"" .. v .. "\""
    end
    return tostring(v)
end
function dump(value, desciption, nesting)
    if type(nesting) ~= "number" then nesting = 3 end

    local lookupTable = {}
    local result = {}

    local function dump_(value, desciption, indent, nest, keylen)
        desciption = desciption or "<var>"
        local spc = ""
        if type(keylen) == "number" then
            spc = string.rep(" ", keylen - string.len(dump_value_(desciption)))
        end
        if type(value) ~= "table" then
            result[#result +1 ] = string.format("%s%s%s = %s", indent, dump_value_(desciption), spc, dump_value_(value))
        elseif lookupTable[tostring(value)] then
            result[#result +1 ] = string.format("%s%s%s = *REF*", indent, dump_value_(desciption), spc)
        else
            lookupTable[tostring(value)] = true
            if nest > nesting then
                result[#result +1 ] = string.format("%s%s = *MAX NESTING*", indent, dump_value_(desciption))
            else
                result[#result +1 ] = string.format("%s%s = {", indent, dump_value_(desciption))
                local indent2 = indent.."    "
                local keys = {}
                local keylen = 0
                local values = {}
                for k, v in pairs(value) do
                    keys[#keys + 1] = k
                    local vk = dump_value_(k)
                    local vkl = string.len(vk)
                    if vkl > keylen then keylen = vkl end
                    values[k] = v
                end
                table.sort(keys, function(a, b)
                    if type(a) == "number" and type(b) == "number" then
                        return a < b
                    else
                        return tostring(a) < tostring(b)
                    end
                end)
                for i, k in ipairs(keys) do
                    dump_(values[k], k, indent2, nest + 1, keylen)
                end
                result[#result +1] = string.format("%s}", indent)
            end
        end
    end
    dump_(value, desciption, "- ", 1)

    for i, line in ipairs(result) do
        print(line)
    end
end


--克隆一个物品
function cloneItem(item)
	local itemName = item:GetItemName()
	local newItem = CreateItem(itemName, nil, nil)
	for k,v in pairs(item.attrs) do
		newItem.attrs[k] = v
	end
end

function CreateNewItem(itemName,opr,posorhero)
	local item = CreateItem(itemName,nil,nil)
	if opr == 0 then
		posorhero:AddItem(item)
	else
		local drop = CreateItemOnPositionSync( posorhero, item )
	    local pos_launch = pos+RandomVector(RandomFloat(150,200))
	    item:LaunchLoot(false, 200, 0.75, pos_launch)
	end
	local attrs = roleData.getAttrEnums()
	item.attrs = {}
	for i,v in ipairs(attrs) do
		local val = item:GetSpecialValueFor(v)
		if val > 0 then
			item.attrs[v] = val
		end
	end
	if string.find(itemName,"item_suit") then
		item.level = 1
	end
end
---------------------------------------------------------------------------
-- GetRandomElement
---------------------------------------------------------------------------
function GetRandomElement( table )
	local nRandomIndex = RandomInt( 1, #table )
    local randomElement = table[ nRandomIndex ]
    return randomElement
end

---------------------------------------------------------------------------
-- ShuffledList
---------------------------------------------------------------------------
function ShuffledList( orig_list )
	local list = shallowcopy( orig_list )
	local result = {}
	local count = #list
	for i = 1, count do
		local pick = RandomInt( 1, #list )
		result[ #result + 1 ] = list[ pick ]
		table.remove( list, pick )
	end
	return result
end

---------------------------------------------------------------------------
-- string.starts
---------------------------------------------------------------------------
function string.starts( string, start )
   return string.sub( string, 1, string.len( start ) ) == start
end

---------------------------------------------------------------------------
-- string.split
---------------------------------------------------------------------------
function string.split( str, sep )
    local sep, fields = sep or ":", {}
    local pattern = string.format("([^%s]+)", sep)
    str:gsub(pattern, function(c) fields[#fields+1] = c end)
    return fields
end

---------------------------------------------------------------------------
-- shallowcopy
---------------------------------------------------------------------------
function shallowcopy(orig)
    local orig_type = type(orig)
    local copy
    if orig_type == 'table' then
        copy = {}
        for orig_key, orig_value in pairs(orig) do
            copy[orig_key] = orig_value
        end
    else -- number, string, boolean, etc
        copy = orig
    end
    return copy
end

---------------------------------------------------------------------------
-- Table functions
---------------------------------------------------------------------------
function PrintTable( t, indent )
	--print( "PrintTable( t, indent ): " )
	if type(t) ~= "table" then return end

	for k,v in pairs( t ) do
		if type( v ) == "table" then
			if ( v ~= t ) then
				print( indent .. tostring( k ) .. ":\n" .. indent .. "{" )
				PrintTable( v, indent .. "  " )
				print( indent .. "}" )
			end
		else
		print( indent .. tostring( k ) .. ":" .. tostring(v) )
		end
	end
end

function TableFindKey( table, val )
	if table == nil then
		print( "nil" )
		return nil
	end

	for k, v in pairs( table ) do
		if v == val then
			return k
		end
	end
	return nil
end

function TableLength( t )
	local nCount = 0
	for _ in pairs( t ) do
		nCount = nCount + 1
	end
	return nCount
end

function tablefirstkey( t )
	for k, _ in pairs( t ) do
		return k
	end
	return nil
end

function tablehaselements( t )
	return tablefirstkey( t ) ~= nil
end

function ConvertToTime( value )
  	local value = tonumber( value )

	if value <= 0 then
		return "00:00:00";
	else
	    hours = string.format( "%02.f", math.floor( value / 3600 ) );
	    mins = string.format( "%02.f", math.floor( value / 60 - ( hours * 60 ) ) );
	    secs = string.format( "%02.f", math.floor( value - hours * 3600 - mins * 60 ) );
	    if math.floor( value / 3600 ) == 0 then
	    	return mins .. ":" .. secs
	    end
	    return hours .. ":" .. mins .. ":" .. secs
	end
end